<?php
namespace app\admin\controller;

use think\Db;

use think\Controller;

class Publish extends Common {

	private $db = null;
	private $config = '';
	private $default_config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $userField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->default_config = config('database');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
	}
	
	
	private function query_where(){
		$params = array();
		if (!empty($_REQUEST)){
			$params = $_REQUEST;
			unset($params['page']);
		}
		$map = "o.order_status=0 and pay_status >0";
		$userPhone = input('get.userPhone');
		$timestamp = input('get.timestamp');
		if ($userPhone) $map .= " and username='{$userPhone}'";
		$selected1 = $selected2 = $selected3 = false;
		switch ($timestamp) {
			case 5:
				$timestamp = time() - 5*60;
				$map .= " and o.time > '{$timestamp}'";
				$selected1 = true;
				break;
			case 10:
				$start_timestamp = time() - 5*60;
				$end_timestamp = time() - 10*60;
				$map .= " and o.time > '{$start_timestamp}' and o.time < '{$end_timestamp}'";
				$selected2 = true;
				break;
			case 11:
				$start_timestamp = time() - 10*60;
				$map .= " and o.time < '{$start_timestamp}'";
				$selected3 = true;
				break;
		}
		return array('params' => $params,'map' => $map,'selected1' => $selected1,'selected2' => $selected2,'selected3' => $selected3);
	}
	
	public function index(){
		$query_where = $this->query_where();
		$data = db('send_order o')->where($query_where['map'])
		->order('time desc')->paginate(config('page_size'), false, array('query' => $query_where['params']));
		$this->assign('lists',$data);
		$this->assign('page',$data->render());
		$this->assign('userPhone',input('get.userPhone'));
		$this->assign('selected1',$query_where['selected1']);
		$this->assign('selected2',$query_where['selected2']);
		$this->assign('selected3',$query_where['selected3']);
		return $this->fetch();
	}
	
	//订单详情
	public function detail(){
		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$orderInfo = db('send_order')->where(array('id' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
		$orderInfo['content'] = json_decode($orderInfo['content'],true);
		$orderInfo['money'] = $orderInfo['money'] + $orderInfo['extra_money'];
		switch ($orderInfo['content']['car']){
			case 1:
				$orderInfo['content']['car_text'] = '摩托车(电动车)';
				break;
			case 2:
				$orderInfo['content']['car_text'] = '小汽车';
				break;
			case 3:
				$orderInfo['content']['car_text'] = '火车';
				break;
		}
		switch ($orderInfo['content']['type']){
			case 1:
				$orderInfo['content']['type_text'] = '帮我送';
				break;
			case 2:
				$orderInfo['content']['type_text'] = '帮我取';
				break;
			case 3:
				$orderInfo['content']['type_text'] = '帮我买';
				break;
		}
		switch ($orderInfo['content']['urgent']){
			case 1:
				$orderInfo['content']['urgent_text'] = '正常配送';
				break;
			case 2:
				$orderInfo['content']['urgent_text'] = '紧急配送';
				break;
		}
		$this->assign($orderInfo);
		return $this->fetch();
	}
	
	public function notcount(){
		$order_id = intval($this->request->get('orderid'));
		if (!$order_id) $this->error('操作失败');
		$order = db('delivery_order')->where(array('id' => $order_id))->find();
		$this->assign('not_layout',true);
		$this->assign($order);
		$issue = db('issue')->select();
		$this->assign('issue',$issue);
		return $this->fetch('notcount');
	}
	
	private function query_string($where){
		$userPhone = $this->request->get('userPhone');
		$account = $this->request->get('account');
		$timeout = $this->request->get('timeout');
		$countstatus = $this->request->get('countstatus');
		if ($userPhone != '') $where .= " and s.username='{$userPhone}'";
		if ($timeout) $where .= " and d.timeout='{$timeout}'";
		if ($countstatus) $where .= " and d.iscount='{$countstatus}'";
		if ($account != ''){
			if (_checkmobile($account)){
				$map = array('mobile' => $account);
			}else{
				$map = array('truename' => $account);
			}
			$user = db('user')->where($map)->find();
			if (empty($user)) $this->error('配送员账号/姓名不存在');
			$where .= " and d.userId='{$user['id']}'";
		}
		$this->assign('userPhone',$userPhone);
		$this->assign('selected',$timeout);
		$this->assign('countstatus',$countstatus);
		$this->assign('account',$account);
		return $where;
	}
	
	private function user($data){
		$uids = array();
		foreach ($data as $key => $value){
			if (!in_array($value['userId'], $uids) && $value['userId'] != 0){
				$uids[] = $value['userId'];
			}
		}
		$user = db('user')->where(array('id' => array('IN',$uids)))->field(array('id','username','mobile','truename'))->select();
		$users = array();
		foreach ($user as $key => $value){
			$users[$value['id']] = $value;
		}
		unset($user);
		$this->assign('user',$users);
	}
	
	public function index2(){
		$where = 'd.user_send=1 and d.status=0';
		$where = $this->query_string($where);
		$this->common_list($where);
		return $this->fetch('index2');
	}
	
	private function common_list($where){
		$query_where = $this->query_where();
		$data = db('send_order s')->join("delivery_order d","s.id=d.orderId")
		->where($where)->field(array("d.*","s.id send_order_id",'s.type','s.uid','s.username','s.pay_status','s.pay_type','s.order_status','s.content','s.send_time','s.time send_order_time','s.money','s.extra_money'))
		->order('s.time desc')->paginate(config('page_size'), false, array('query' => $query_where['params']));
		$temp = array();
		foreach ($data as $key => $value){
			$value['content'] = json_decode($value['content'],true);
			$temp[] = $value;
		}
		$this->assign('lists',$temp);
		$this->user($temp);
		$this->assign('page',$data->render());
	}
	
	public function index3(){
		$query_where = $this->query_where();
		$where = 'd.user_send=1 and d.status=1';
		$where = $this->query_string($where);
		$this->common_list($where);
		return $this->fetch('index2');
	}
	
	public function index4(){
		$query_where = $this->query_where();
		$where = 'd.user_send=1 and d.status=2';
		$where = $this->query_string($where);
		$this->common_list($where);
		return $this->fetch('index2');
	}
	
	public function index5(){
		$query_where = $this->query_where();
		$where = 'd.user_send=1 and d.status=3';
		$where = $this->query_string($where);
		$this->common_list($where);
		return $this->fetch('index2');
	}
	
	public function index6(){
		$query_where = $this->query_where();
		$where = 'd.user_send=1 and d.iscancel=1';
		$where = $this->query_string($where);
		$this->common_list($where);
		return $this->fetch('index2');
	}
	
	public function run_notcount(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$issue = db('issue')->where(array('id' => $this->request->post('type')))->find();
		//$issue['type'] 1: 订单不结算配送原因 2: 更换配送员原因
		$data = array(
			'orderid' => $order_id,
			'type' => $this->request->post('type'),
			'uid' => $this->request->post('uid'),
			'admin_uid' => $this->userinfo['id'],
			'content' => $this->request->post('content'),
			'status' => 0,
			'time' => time(),
		);
		if ($data['content'] == '') $this->ajaxReturn(array('code' => 0,'msg' => '请输入消息内容'));
		if ($issue['type'] == 1){
			db('delivery_order')->where(array('id' => $order_id))->setField('iscount',2);
		}else{
			db('delivery_order')->where(array('id' => $order_id))->setField('timeout',2);
		}
		if (db('user_msg')->insert($data)){
			$this->ajaxReturn(array('code' => 1,'msg' => '操作成功'));
		}else{
			$this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		}
	}
	
	public function updateuser(){
		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$order = db('delivery_order')->where(array('id' => $orderId))->find();
		$this->assign($order);
		$orderId = $order['orderId'];
		$orderInfo = db('send_order')->where(array('id' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
		$address_section = db('address_section')->select();
		$userlists = db('user')->where(array('status' => 1,'check_status' => 1))->field(array('id','username','truename','mobile','user_face'))->select();
		$this->assign('userlist',$userlists);
		$this->assign('orderInfo',$orderInfo);
		$issue = db('issue')->select();
		$this->assign('issue',$issue);
		return $this->fetch();
	}
	
	public function run_user(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$user_id = intval($this->request->post('user_id'));
		$issue = db('issue')->where(array('id' => $this->request->post('type')))->find();
		//$issue['type'] 1: 订单不结算配送原因 2: 更换配送员原因
		$data = array(
			'orderid' => $order_id,
			'type' => $this->request->post('type'),
			'uid' => $this->request->post('uid'),
			'admin_uid' => $this->userinfo['id'],
			'content' => $this->request->post('content'),
			'status' => 0,
			'time' => time(),
		);
		$order = db('delivery_order')->where(array('id' => $order_id))->find();
		if ($user_id == $order['userId']){
			$this->ajaxReturn(array('code' => 0,'msg' => '请选择一个新的配送员'));
		}
		if ($data['content'] == '') $this->ajaxReturn(array('code' => 0,'msg' => '请输入消息内容'));
		if (!$user_id) $this->ajaxReturn(array('code' => 0,'msg' => '请选择配送员'));
		$user = db('user')->where(array('id' => $user_id,'status' => 1,'check_status' => 1))->field(array('id','mobile'))->find();
		if (empty($user)) $this->ajaxReturn(array('code' => 0,'msg' => '配送员不存在'));
		if ($issue['type'] == 1){
			db('delivery_order')->where(array('id' => $order_id))->setField('iscount',2);
		}else{
			db('delivery_order')->where(array('id' => $order_id))->setField('timeout',2);
			// 唐峰康改
			// 更改配送员 1 is_change
			db('delivery_order')->where(array('id' => $order_id))->setField('is_change',1);
		}
		db('delivery_order')->where(array('id' => $order_id))->setField('userId',$user_id);
		if (db('user_msg')->insert($data)){
			$this->ajaxReturn(array('code' => 1,'msg' => '操作成功'));
		}else{
			$this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		}
	}
	
	//派单
	public function send_order(){

		// 唐峰康改 获取待抢单目的地和配送员的距离范围
		$distanceInfo = $this->db->name('sys_configs')->where(array('fieldCode'=>'showdistance'))->find();
		$show_distance = $distanceInfo['fieldValue'];
		// echo $show_distance;

		$this->assign('not_layout',true);
		$orderId = $this->request->param('orderid');
		if (!$orderId) $this->error('订单不存在');
		$orderInfo = db('send_order')->where(array('id' => $orderId))->find();
		if (!$orderInfo) $this->error('订单不存在');
		$orderInfo['content'] = json_decode($orderInfo['content'],true);
		if ($orderInfo['type'] == 3){
			$lng = $orderInfo['content']['buy_lng'];
			$lat = $orderInfo['content']['buy_lat'];
		}else{
			$lng = $orderInfo['content']['go_lng'];
			$lat = $orderInfo['content']['go_lat'];
		}
		
		//$right>lng and $left<lng
		$right = round($lng,2);
		$left= substr(sprintf("%.4f",$lng),0,-1);
		// $where = "status=1 and check_status=1 and `lng`<'{$right}' and '{$left}'>`lng` and lng != ''";
		$where = "status=1 and check_status=1";
		$userlists = db('user')->where($where)->field(array('id','username','truename','mobile','user_face','lat','lng'))->select();
		// 唐峰康改 过滤不在范围内的
		foreach ($userlists as $k => $v) {
			$distance = $this->getTwoClockDistance($v['lat'],$v['lng'],$lat,$lng);
			if ($distance > $show_distance) {
				unset($userlists[$k]);
			}

		}
		$this->assign('userlist',$userlists);
		$this->assign('orderInfo',$orderInfo);
		return $this->fetch();
	}
	
	//派单到配送
	public function send_order_run(){
		if (!request()->isAjax()) $this->error('操作失败');
		$order_id = intval($this->request->post('orderId'));
		$user_id = intval($this->request->post('user_id'));
		if (!$user_id) $this->ajaxReturn(array('code' => 0,'msg' => '请选择配送员'));
		$user = db('user')->where(array('id' => $user_id,'status' => 1,'check_status' => 1))->field(array('id','mobile'))->find();
		if (empty($user)) $this->ajaxReturn(array('code' => 0,'msg' => '配送员不存在'));
		$map = array('id' => $order_id);
		$orderInfo = db('send_order')->where($map)->find();
		if (empty($orderInfo)) $this->ajaxReturn(array('code' => 0,'msg' => '订单不存在'));
		$delivery_order = db('delivery_order');
		$inOrder = $delivery_order->where(array('orderId' => $orderInfo['id'],'user_send' => 1))->count();
		if ($inOrder > 0) $this->ajaxReturn(array('code' => 0,'msg' => '订单已派单'));



		$orderInfo['content'] = json_decode($orderInfo['content'],true);
		// 夜间配送费
		$extra_money = $orderInfo['extra_money'];
		// 配送员夜间配送提成
		$proportion = $orderInfo['proportion'];
		$user_delivery_config = db('system')->where(array('name' => 'delivery_user_config'))->find();
			$user_delivery_config = unserialize($user_delivery_config['value']);
			$order = [];
			if ($orderInfo['type'] == 3){
				$order['my_location'] = subMoney(getDistance($orderInfo['user_lat'], $orderInfo['user_lng'], $orderInfo['content']['buy_lat'], $orderInfo['content']['buy_lng']));
				$order['to_location'] = subMoney(getDistance($orderInfo['content']['buy_lat'], $orderInfo['content']['buy_lng'], $orderInfo['content']['get_lat'], $orderInfo['content']['get_lng']));
			}else{
				$order['my_location'] = subMoney(getDistance($orderInfo['user_lat'], $orderInfo['user_lng'], $orderInfo['content']['go_lat'], $orderInfo['content']['go_lng']));
				$order['to_location'] = subMoney(getDistance($orderInfo['content']['go_lat'], $orderInfo['content']['go_lng'], $orderInfo['content']['get_lat'], $orderInfo['content']['get_lng']));
			}
			foreach ($user_delivery_config as $k => $j){
				if ($j['go_distance'] >= $order['to_location']){
					switch ($orderInfo['content']['car']){
						case 1:
							$orderInfo['money'] = $j['go_shop_money'];
							break;
						case 2:
							$orderInfo['money'] = $j['go_shop_money2'];
							break;
						case 3:
							$orderInfo['money'] = $j['go_shop_money2'];
							break;
					}
					break;
				}
			}
		$delivery_order_num = 'PS'. date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);//add by hfc 5.12
		if ($extra_money > 0) {
			$orderInfo['money'] =$orderInfo['money'] + $extra_money * $proportion;
		}
			
		$insertData = array(
				'userId' => $user['id'],
				'shopId' => 0,
				'orderId' => $orderInfo['id'],
				'status' => 0,
				'time' => time(),
				'user_send' => 1,//add by hfc 5.12
				'delivery_order_num'=>$delivery_order_num,//add by hfc 5.12
				"buyerLngLat"=>$orderInfo['user_lng'].','.$orderInfo['user_lat'],//add by hfc 5.12
				'deliverMoney'=>$orderInfo['money'],
				'require_time'=>$orderInfo['send_time']
		);


		$data = array('code' => 0,'msg' => '派单失败');
		$delivery_order_id = $delivery_order->insertGetId($insertData);
		if ($delivery_order_id) {
			$data = array('code' => 1,'msg' => '派单成功');
			db('send_order')->where($map)->setField('order_status',1);
			$user_mobile = $user['mobile'];
			// 旧
			// $orderId = $orderInfo['orderId'];
			// 唐峰康改 推送消息 跳转APP详情页必须是 delivery_order里 的主键id
			$orderId = $delivery_order_id;
			require $_SERVER['DOCUMENT_ROOT'] . '/vendor/' . 'JpushSend.class.php';
			$receive['alias'][] = $user_mobile;
			$chattitle = '新信息';
			$content = '您有新的订单';
			$content = $chattitle . ":" . $content;
			$fetion = new \JpushSend();
			$m_type = 'paotui';
			$m_txt = array('orderId' => $orderId);
			$m_time = '600'; //默认
			$res = $fetion->sendPub($receive, $content, $m_type, $m_txt, $m_time);
		}
		
		$this->ajaxReturn($data);
	}

	// 唐峰康改 根据两点之间的经纬度 获取距离

    /**
	 *	计算两经纬度之间的距离（km）
	 **/
	public function getTwoClockDistance($lat1, $lng1, $lat2, $lng2, $len_type = 2, $decimal = 2) {

	    $EARTH_RADIUS = 6378.137;
	    $PI = 3.1415926;
	    $radLat1 = $lat1 * $PI / 180.0;
	    $radLat2 = $lat2 * $PI / 180.0;
	    $a = $radLat1 - $radLat2;
	    $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
	    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
	    $s = $s * $EARTH_RADIUS;
	    $s = round($s * 1000);
	    if ($len_type > 1) {
	        $s /= 1000;
	    }
	    return round($s, $decimal);
	}  
	
}